import android.util.Log
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.InetSocketAddress
import java.net.Socket
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

internal class TCPClient {
    private var socket: Socket? = null
    private var inputStream: InputStream? = null
    private var outputStream: OutputStream? = null
    private val executor: ExecutorService = Executors.newSingleThreadExecutor()
    private var isConnected = false
    private var statusListener: OnStatusListener? = null
    private var byteArrayListener: OnByteArrayListener? = null
    private val connectLock = Any() // 线程锁

    interface OnStatusListener {
        fun onStatus(isConnected: Boolean, error: String?)
    }

    interface OnByteArrayListener {
        fun onByteArray(bytes: ByteArray?)
    }

    interface OnSendListener {
        fun onSendSuccess()
        fun onSendFailed(error: String)
    }
    fun isConnected(): Boolean {
        return isConnected
    }
    fun setStatusListener(listener: OnStatusListener) {
        this.statusListener = listener
    }

    fun setByteArrayListener(listener: OnByteArrayListener?) {
        this.byteArrayListener = listener
    }

    fun connect(host: String, port: Int, timeout: Int) {
        Log.w("TCPClient", "准备连接，connect")
        executor.submit {
            synchronized(connectLock) {
                if (isConnected) {
                    Log.w("TCPClient", "已连接，跳过重复连接")
                    return@submit
                }

                try {
                    socket = Socket()
                    socket!!.connect(InetSocketAddress(host, port), timeout)
                    Log.d("TCPClient", "Socket 连接成功")

                    inputStream = socket!!.getInputStream()
                    outputStream = socket!!.getOutputStream()

                    if (outputStream == null) {
                        throw IOException("输出流初始化失败")
                    }
                    Log.d("TCPClient", "输入输出流初始化完成")
                    isConnected = true
                    Log.d("TCPClient", "设置连接状态为 true")
                    statusListener?.onStatus(true, null)
                    startReceiveThread()
                } catch (e: Exception) {
                    isConnected = false
                    val errorMsg = when (e) {
                        is java.net.ConnectException -> "连接被拒绝，请检查服务器地址和端口"
                        is java.net.SocketTimeoutException -> "连接超时，请检查网络连接"
                        is java.net.UnknownHostException -> "未知主机，请检查IP地址"
                        else -> "连接失败: ${e.message}"
                    }
                    statusListener?.onStatus(false, errorMsg)
                }
            }
        }
    }

    fun disconnect() {
        executor.submit {
            synchronized(connectLock) {
                if (!isConnected) {
                    return@submit
                }

                try {
                    inputStream?.close()
                    outputStream?.close()
                    socket?.close()
                    isConnected = false
                    statusListener?.onStatus(false, null)
                } catch (e: IOException) {
                    Log.e("TCPClient", "断开连接异常：${e.message}", e)
                }
            }
        }
    }

    fun sendData(bytes: ByteArray, sendListener: OnSendListener? = null) {
        executor.submit {
            synchronized(connectLock) {
                if (!isConnected) {
                    Log.e("TCPClient", "发送失败：未连接")
                    sendListener?.onSendFailed("未连接到服务器")
                    return@submit
                }

                if (socket == null || socket!!.isClosed) {
                    Log.e("TCPClient", "发送失败：Socket已关闭")
                    sendListener?.onSendFailed("Socket已关闭")
                    return@submit
                }

                if (outputStream == null) {
                    Log.e("TCPClient", "发送失败：输出流为空")
                    sendListener?.onSendFailed("输出流为空")
                    return@submit
                }
            }

            Log.d("TCPClient", "【发送数据】准备发送：${byteArrayToHexString(bytes)} (长度: ${bytes.size}字节)")
            try {
                outputStream!!.write(bytes)
                outputStream!!.flush()
                Log.d("TCPClient", "【发送数据】成功发送")
                sendListener?.onSendSuccess()
            } catch (e: IOException) {
                Log.e("TCPClient", "发送异常：${e.message}", e)
                sendListener?.onSendFailed(e.message ?: "发送失败")
                statusListener?.onStatus(false, "发送失败: ${e.message}")
                disconnect()
            }
        }
    }

    private fun startReceiveThread() {
        executor.submit {
            val buffer = ByteArray(4096)
            try {
                while (isConnected && socket != null && !socket!!.isClosed) {
                    val len = inputStream?.read(buffer) ?: -1
                    if (len > 0) {
                        val data = ByteArray(len)
                        System.arraycopy(buffer, 0, data, 0, len)
                        Log.d("TCPClient", "【接收数据】收到：${byteArrayToHexString(data)} (长度: ${len}字节)")
                        byteArrayListener?.onByteArray(data)
                    }
                }
            } catch (e: IOException) {
                Log.e("TCPClient", "接收异常：${e.message}", e)
                isConnected = false
                statusListener?.onStatus(false, "接收失败: ${e.message}")
                disconnect()
            }
        }
    }

    fun byteArrayToHexString(bytes: ByteArray): String {
        val result = StringBuilder()
        for (b in bytes) {
            result.append(String.format("%02X", b))
        }
        return result.toString()
    }

    fun hexStringToByteArray(s: String): ByteArray {
        val len = s.length
        val data = ByteArray(len / 2)
        var i = 0
        while (i < len) {
            data[i / 2] = ((((s[i].digitToIntOrNull(16) ?: (-1 shl 4)) + s[i + 1].digitToIntOrNull(16)!!) ?: -1)).toByte()
            i += 2
        }
        return data
    }

    // 新增清空监听器方法
    fun clearListeners() {
        statusListener = null
        byteArrayListener = null
    }
}